#include "relayitem.h"
#include <QPainter>
#include <QGraphicsSceneMouseEvent>

Relay::Relay(bool closed, QGraphicsItem *parent)
    : CircuitComponent(parent)
    , m_closed(closed)
{
    setFlag(QGraphicsItem::ItemIsSelectable); // 可选
    setFlag(QGraphicsItem::ItemIsFocusable);  // 可聚焦
}

QPointF Relay::inputPort() const
{
    return QPointF(-30, 0);
}

QPointF Relay::outputPort() const
{
    return QPointF(30, 0);
}

QRectF Relay::boundingRect() const
{
    return QRectF(-25, -10, 50, 20); // 精确匹配可视区域
}

void Relay::setClosed(bool closed)
{
    if(m_closed != closed) {
        m_closed = closed;
        update(); // 触发重绘
        // 可以在此处添加状态改变信号
        if(m_text.compare("主正继电器") == 0) {
            emit changeStateMainZ(closed);
        } else if(m_text.compare("预充继电器") == 0) {
            emit changeStatePrevC(closed);
        } else if(m_text.compare("充电继电器") == 0) {
            emit changeStateFastC(closed);
        } else if(m_text.compare("主负继电器") == 0) {
            emit changeStateMainF(closed);
        }
    }
}

void Relay::setText(const QString &text)
{
    m_text = text;
}

void Relay::setEnable(bool enable)
{
    m_enable = enable;
}

void Relay::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    Q_UNUSED(option);
    Q_UNUSED(widget);

    painter->setRenderHint(QPainter::Antialiasing);

    // 绘制主体
    painter->setPen(QColor(m_closed ? Qt::green : Qt::red));
    painter->drawRect(-25, -10, 50, 20);    

    // 绘制开关状态
    if(m_closed) {
        painter->drawLine(-25, 0, 25, 0); // 闭合状态
    } else {
        painter->drawLine(-25, 10, 25, -10); // 断开状态
    }

    // 绘制端口（可选）
    painter->drawRect(-35, -5, 10, 10); // 输入端口
    painter->drawRect(25, -5, 10, 10);  // 输出端口

    painter->setPen(QPen(Qt::white));
    //绘制文本信息
    painter->drawText(QRect(-29, -30, 80, 20), Qt::AlignLeft,m_text);
}

void Relay::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    if(!m_enable) {
        return;
    }

    // 左键点击切换状态
    if(event->button() == Qt::LeftButton) {
        setClosed(!m_closed);
        event->accept(); // 阻止事件继续传递
    } else {
        QGraphicsItem::mousePressEvent(event);
    }

    update();
}
